import { ModalForm, ProFormSelect, ProFormText } from '@ant-design/pro-components';
import type { FormInstance } from '@ant-design/pro-components';
import { useRef } from 'react';
import { useModel } from 'umi';
import type { CreateSensorDeviceType } from '../types.d';
import { Button, message } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { createSensorDevice } from '../service';
import { standardReg } from '@/utils/utils';
import { Role } from '@/utils/types.d';
import { queryCompanies } from '@/pages/SystemUser/service';

export default (props: { reload: () => void }) => {
  const { initialState } = useModel('@@initialState');
  const userRole = initialState?.currentUser?.role;
  const formRef = useRef<FormInstance>();
  return (
    <ModalForm<CreateSensorDeviceType>
      title="添加地磁设备"
      layout="horizontal"
      width="40vw"
      formRef={formRef}
      modalProps={{
        destroyOnClose: true,
      }}
      labelCol={{ span: 6 }}
      wrapperCol={{ span: 14 }}
      trigger={
        <Button type="primary">
          <PlusOutlined /> 添加设备
        </Button>
      }
      onFinish={async (values) => {
        const res = await createSensorDevice(values);
        if (res.success) {
          message.success({
            content: res.message,
            key: 'add_sensorDevice',
          });
          props.reload();
          formRef.current?.resetFields();
          return true;
        }
        message.error({
          content: res.message,
          key: 'add_sensorDevice',
        });
        return false;
      }}
    >
      <ProFormText
        label="地磁编号"
        width="xl"
        name="deviceSn"
        rules={[
          {
            required: true,
            validator: (_, val) => {
              if (!standardReg.test(val)) return Promise.reject(new Error('设备编号无效'));
              return Promise.resolve(val);
            },
          },
        ]}
        placeholder="请输入设备编号"
      />
      <ProFormSelect
        label="地磁厂家"
        width="xl"
        name="manufacturer"
        placeholder="请输入地磁厂家"
        initialValue="目博地磁"
        options={[
          { value: '目博地磁', label: '目博地磁' },
          { value: '帕玛地磁', label: '帕玛地磁' },
        ]}
      />
      {userRole === Role.ADMIN && (
        <ProFormSelect
          name="ownerId"
          width="xl"
          label="归属公司"
          debounceTime={300}
          showSearch
          placeholder="请选择归属公司(如未找到目标公司，请优先创建[企业管理者])"
          request={(val) => queryCompanies(val.keyWords)}
        />
      )}
    </ModalForm>
  );
};
